﻿using AppFlat.Application.IService;
using AppFlat.Domain.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Newtonsoft.Json;
using AppFlat.Domain.DTO;
using AppFlat.Common.Jwt;

namespace AppFlat.UI.WebApi.Controllers
{
    public class DevUsersController : ApiController
    {
        public IDevUserService userApp { get; set; }

        [Route("api/dev/login")]
        public async Task<IHttpActionResult> Login([FromBody]DevUserLoginDTO dto)
        {
            var user = await userApp.GetEntityAsync(u => u.Name == dto.Name && u.Password == dto.Password);
            if (user!=null)
            {
                double exp = (DateTime.UtcNow.AddMinutes(20) - new DateTime(1970, 1, 1)).TotalSeconds;
                //进行组装
                var payload = new Dictionary<string, object>
                {
                  {"userId", user.Id },
                  {"userName", user.Name },
                  {"exp",exp }
                };
                //2. 进行JWT签名
                var token = JwtHelper.JiaM(payload);

                return Json(new { code = 0, msg = "登录成功", data = token });

            }
            else
            {
                return Json(new { code = 1, msg = "账号或密码错误！", data="" });
            }
        }

        public async Task<IHttpActionResult> GetUsers(string name,int pageIndex=1, int pageSize=8)
        {
            string userName = "";
            if (!string.IsNullOrEmpty(name))
                userName = name;
            int total;
            var result = await userApp.GetEntities(pageIndex, pageSize, out total, u => u.Name.Contains(userName), u => u.Id, true)
                .Select(u => new { u.Id, u.Name, u.State, u.Email })
                .ToListAsync();
            return Json(new { code=0, msg="",count=total,data=result});
            
        }

        public async Task<IHttpActionResult> Post([FromBody]DevUser devUser)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest("信息填写不符合要求");
            }

            var result=await  userApp.AddAsync(devUser);
            if (result)
                return Ok("添加完成！");

            return Content(HttpStatusCode.InternalServerError,devUser);  // 500错误
        }

        [HttpGet]
        [Route("api/DevUsers/changestate/{id}")]
        public IHttpActionResult ChangeState(int? id)
        {
            if (!id.HasValue)
                return BadRequest();

            if (userApp.ChangeState(id.Value))
                return Ok();
            return NotFound();

        }
        [HttpGet]
        [Route("api/DevUsers/Efchangestate/{id}")]
        public IHttpActionResult ChangeState(int? id, int state)
        {
            if (!id.HasValue)
                return BadRequest();

            if (userApp.EFChangeState(id.Value,state))
                return Ok();
            return NotFound();
        }


        public async Task<IHttpActionResult> Delete(int? id)
        {
            if (!id.HasValue)
                return BadRequest();

            var result=await userApp.DeleteAsync(new DevUser() { Id = id.Value });
            if (result)
                return Ok();
            return NotFound();
        }

        public async Task<IHttpActionResult> Get(int? id)
        {

            var user = await userApp.GetEntityAsync(n => n.Id == id);

            JsonSerializerSettings setting = new JsonSerializerSettings();
            setting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;  //
            return Json(user,setting);
        }
    }
}
